package com.yjw.demo.netty.bio;

import com.yjw.demo.netty.util.IoUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Random;

/**
 * 客户端
 *
 * @author yinjianwei
 * @date 2018/11/13
 */
public class Client {

    private static final String DEFAULT_SERVER_IP = "127.0.0.1";
    private static final int DEFAULT_SERVER_PORT = 8888;

    public static void main(String[] args) throws Exception {
        char[] op = {'+', '-', '*', '/'};
        Random random = new Random();
        for (int i = 0; i < 5; i++) {
            Client.send(random.nextInt(100) + "" + op[random.nextInt(4)] + random.nextInt(100));
            Thread.sleep(1000);
            System.out.println();
        }
    }

    /**
     * 客户端发送消息
     *
     * @param expression 表达式
     */
    public static void send(String expression) {
        Socket socket = null;
        PrintWriter pw = null;
        BufferedReader br = null;
        try {
            socket = new Socket(DEFAULT_SERVER_IP, DEFAULT_SERVER_PORT);
            br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            pw = new PrintWriter(socket.getOutputStream(), true);
            // 发送表达式
            pw.println(expression);
            // 接收计算结果
            String result = br.readLine();
            System.out.println("表达式：" + expression);
            System.out.println("服务端计算结果：" + result);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            IoUtils.close(br, pw, socket);
        }
    }
}
